package com.cauli.search.component;

import com.alibaba.fastjson.JSON;
import com.cauli.search.model.dto.FileSearchDTO;
import com.cauli.search.service.ElasticsearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Cauli
 * @date 2023/9/2 15:39
 * @description 消息队列监听
 */
@Slf4j
@Component
public class FileMQListener {
    // 普通交换机
    public static final String FILE_EXCHANGE = "file.exchange";

    // 文件保存相关
    public static final String QUEUE_FILE_SAVE = "queue.file.save";
    public static final String KEY_FILE_SAVE = "key.file.save";

    // 文件删除相关
    public static final String QUEUE_FILE_REMOVE = "queue.file.remove";
    public static final String KEY_FILE_REMOVE = "key.file.remove";

    @Autowired
    private ElasticsearchService elasticsearchService;

    /**
     * 监听文件信息添加操作
     *
     * @param fileSearchDTO
     */
    @RabbitListener(bindings = {@QueueBinding(
            key = KEY_FILE_SAVE,
            value = @Queue(value = QUEUE_FILE_SAVE, durable = "true"),
            exchange = @Exchange(value = FILE_EXCHANGE, type = ExchangeTypes.TOPIC, ignoreDeclarationExceptions = "true"))})
    public void receiveFileSaveMessage(FileSearchDTO fileSearchDTO) {
        try {
            log.info("监听到文件信息添加操作：{}", fileSearchDTO);
            // 更新ES数据
            elasticsearchService.uploadES(fileSearchDTO);
            log.info("添加完成：{}", fileSearchDTO);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 监听文件信息删除操作
     *
     * @param userFileId
     */
    @RabbitListener(bindings = {@QueueBinding(
            key = KEY_FILE_REMOVE,
            value = @Queue(value = QUEUE_FILE_REMOVE, durable = "true"),
            exchange = @Exchange(value = FILE_EXCHANGE, type = ExchangeTypes.TOPIC, ignoreDeclarationExceptions = "true"))})
    public void receiveFileDeleteMessage(Long userFileId) {
        try {
            log.info("监听到文件信息删除操作：{}", userFileId);
            // 删除ES数据
            elasticsearchService.deleteES(userFileId);
            log.info("文件信息删除完成：{}", userFileId);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
